package com.pipayshop.config;

import com.alibaba.fastjson.JSON;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.pipayshop.entity.AccountInfo;
import com.pipayshop.entity.Transfer;
import com.pipayshop.entity.UserInfo;
import com.pipayshop.mapper.UserAccountInfoMapper;
import com.pipayshop.mapper.UserInfoMapper;
import jakarta.annotation.Resource;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class eCNYTransferQueueComsuner {
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private UserAccountInfoMapper userAccountInfoMapper;

    @RabbitListener(queues = "eCNYTransfer")
    public void eCNYTransferQueue(String msg){
        Transfer transfer = JSON.parseObject(msg, Transfer.class);
        // TODO 充值积分业务代码
        String transferTo = transfer.getTo();
        String value = transfer.getValue();
        double valueInDecimal = Double.parseDouble(value) / Math.pow(10, 6);  // 除以10的6次方
        // 格式化为6位小数
        String formattedValue = String.format("%." + 6 + "f", valueInDecimal);
        System.out.println("transferTo:"+transferTo);
        System.out.println("formattedValue:"+formattedValue);
        UserInfo userInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getWalletAddress, transferTo));
        if (userInfo != null){
            // 更新用户积分
            int update = userAccountInfoMapper.update(null, new LambdaUpdateWrapper<AccountInfo>()
                    .eq(AccountInfo::getUid, userInfo.getUid())
                    .setSql("point_balance = point_balance + " + formattedValue));
            if (update <= 0) {
                throw new RuntimeException("充值失败");
            }
        }
    }

}
